<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue';
import {useRoute} from "vue-router";
import axios from '@/utils/axios.ts';
import {showToast} from "vant";
import PostCard from '../components/PostCard.vue';

const route = useRoute();
const userId = ref(route.params.userId);
const isLoading = ref(true);
const activeTab = ref('posts'); // 默认显示帖子标签

const data = reactive({
  user: {
    userId: 0,
    nickname: "",
    avatar: "",
    level: 0,
    signature: "",
    registerTime: "",
    postCount: 0,
    followerCount: 0,
    followingCount: 0,
    isFollowing: false
  },
  userPosts: [],
  userPosts2: [],
  tabs: [
    { name: 'posts', title: '动态', count: 0 },
    { name: 'posts2', title: '作品', count: 0 },
  ]
});

// 获取用户信息
const fetchUserData = () => {
  try {
    isLoading.value = true;
    axios.get("/api/users/getUserById?id="+userId.value)
        .then(res=>{
          if (res.code === 200) {
            data.user = res.data;
          }
        })

    // 获取用户帖子
    fetchUserPosts();
  } catch (err) {
    console.log("获取用户信息失败:", err);
  } finally {
    isLoading.value = false;
  }
};

// 获取用户发布的帖子
const fetchUserPosts = async () => {
  try {
    const res = await axios.get("/api/posts/getUserPosts?id="+userId.value);
    data.userPosts = res.data;
    data.userPosts2 =res.data.filter(post => post.contentType === 2);
    data.tabs[0].count = res.data.length;
    data.tabs[1].count = data.userPosts2.length;

  } catch (err) {
    console.error("获取用户帖子失败:", err);
    showToast("加载帖子失败");
  }
};

// 关注/取消关注用户
const toggleFollow = async () => {
  try {
    // 获取当前登录用户ID（使用token获取用户信息）
    const token = localStorage.getItem('token');
    if (!token) {
      showToast("请先登录");
      return;
    }

    // 使用token获取当前用户信息
    let currentUserId;
    try {
      // 仿照 getCurrentUser 的方式，向 /users/current 发送请求获取当前用户信息
      const currentUserRes = await axios.get("/api/users/current", {
        headers: { 'Authorization': `Bearer ${token}` }
      });

      if (currentUserRes.code === 200) {
        currentUserId = currentUserRes.data.userId;
      } else {
        showToast("获取用户信息失败");
        return;
      }
    } catch (error) {
      console.error("获取当前用户信息失败:", error);
      showToast("请先登录");
      return;
    }

    if (!currentUserId) {
      showToast("请先登录");
      return;
    }

    // 调用后端接口更新关注状态
    // isCancel: 0表示关注，1表示取消关注
    const isCancel = data.user.isFollowing ? 1 : 0;

    const res = await axios.post("/api/follows/updateFollowById", null, {
      params: {
        followerId: currentUserId,     // 当前用户ID（关注者）
        followeeId: data.user.userId,  // 被关注用户ID
        isCancel: isCancel             // 0:关注, 1:取消关注
      }
    });

    if (res.code === 200) {
      // 更新前端状态
      data.user.isFollowing = !data.user.isFollowing;
      data.user.followerCount += data.user.isFollowing ? 1 : -1;
      showToast(data.user.isFollowing ? "关注成功" : "已取消关注");
    } else {
      showToast(res.msg || "操作失败");
    }
  } catch (error) {
    console.error("关注操作失败:", error);
    showToast("操作失败，请重试");
  }
};

// 时间格式化函数
const formatTime = (timestamp: string): string => {
  const now = new Date();
  const registerTime = new Date(timestamp);
  const diffInDays = Math.floor((now.getTime() - registerTime.getTime()) / (1000 * 60 * 60 * 24));

  if (diffInDays < 30) {
    return `${diffInDays}天前加入`;
  }
  if (diffInDays < 365) {
    return `${Math.floor(diffInDays / 30)}个月前加入`;
  }
  return `${Math.floor(diffInDays / 365)}年前加入`;
};

onMounted(() => {
  fetchUserData();
});
</script>

<template>
  <div class="user-detail-container">
    <!-- 顶部导航栏 -->
    <div class="nav-header">
      <van-icon name="arrow-left" class="back-button" @click="$router.back()" />
      <span class="page-title"><img src="/slhao.svg" style="height: 30px"></span>
    </div>
    <!-- 加载状态 -->
    <van-loading v-if="isLoading" class="page-loading" type="spinner" color="#1989fa" />

    <template v-else>
      <!-- 用户信息头部 -->
      <div class="user-header">
        <div class="user-avatar-section">
          <img
              :src="data.user.avatar || '/userTx.svg'"
              alt="用户头像"
              class="user-avatar"
          />
        </div>

        <div class="user-info">
          <div class="user-name-section">
            <h2 class="user-name">{{ data.user.nickname||"未知用户" }}</h2>
            <span
                class="rank-badge"
                :class="`rank-${data.user.level}`"
            >
              Lv.{{ data.user.level }}
            </span>
          </div>

          <p class="user-signature">{{ data.user.signature || "这个人很懒，什么都没留下~" }}</p>

          <div class="user-meta">
            <span class="join-time">{{ formatTime(data.user.registerTime) }}</span>
          </div>
        </div>

        <div class="follow-section">
          <button
              class="follow-button"
              :class="{ 'following': data.user.isFollowing }"
              @click="toggleFollow"
          >
            {{ data.user.isFollowing ? "已关注" : "关注" }}
          </button>
        </div>
      </div>

      <!-- 用户统计数据 -->
      <div class="user-stats">
        <div class="stat-item">
          <div class="stat-value">{{ data.user.postCount }}</div>
          <div class="stat-label">作品</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ data.user.followerCount }}</div>
          <div class="stat-label">粉丝</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ data.user.followingCount }}</div>
          <div class="stat-label">关注</div>
        </div>
      </div>

      <!-- 内容标签页 -->
      <van-tabs v-model:active="activeTab" class="content-tabs">
        <van-tab v-for="tab in data.tabs" :key="tab.name" :title="`${tab.title} ${tab.count}`" :name="tab.name">
          <!-- 帖子列表 -->
          <div v-if="activeTab === 'posts'" class="user-posts">
            <div v-if="data.userPosts.length > 0">
              <PostCard
                  v-for="post in data.userPosts"
                  :key="post.postId"
                  :post="post"
                  :user-data="data.user"
                  class="post-item"
              />
            </div>
            <div v-else class="empty-content">
              <van-empty description="该用户还没有动态" />
            </div>
          </div>

          <!-- 作品列表 -->
          <div v-if="activeTab === 'posts2'" class="user-posts">
            <div v-if="data.userPosts2.length > 0">
              <PostCard
                  v-for="post in data.userPosts2"
                  :key="post.postId"
                  :post="post"
                  :user-data="data.user"
                  class="post-item"
              />
            </div>
            <div v-else class="empty-content">
              <van-empty description="该用户还没有作品" />
            </div>
          </div>
        </van-tab>
      </van-tabs>
    </template>
  </div>
</template>

<style scoped>
.user-detail-container {
  padding-bottom: 20px;
  background-color: #f7f8fa;
  min-height: 100vh;
}

.page-loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.user-header {
  display: flex;
  padding: 20px;
  background-color: #fff;
  border-bottom: 1px solid #f0f0f0;
}

.user-avatar-section {
  margin-right: 16px;
}

.user-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
}

.user-info {
  flex: 1;
}

.user-name-section {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.user-name {
  font-size: 18px;
  font-weight: bold;
  margin: 0;
  margin-right: 8px;
}

.rank-badge {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  background-color: #f0f0f0;
  color: #666;
}

.user-signature {
  margin: 0 0 8px;
  color: #666;
  font-size: 14px;
  line-height: 1.4;
}

.user-meta {
  font-size: 12px;
  color: #999;
}

.join-time {
  display: block;
}

.follow-section {
  display: flex;
  align-items: center;
}

.follow-button {
  padding: 6px 16px;
  border-radius: 20px;
  background-color: #1989fa;
  color: white;
  border: none;
  font-size: 14px;
  cursor: pointer;
}

.follow-button.following {
  background-color: #f0f0f0;
  color: #333;
}

.user-stats {
  display: flex;
  justify-content: space-around;
  padding: 16px 0;
  background-color: #fff;
  margin-bottom: 10px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #666;
}

.content-tabs {
  background-color: #fff;
}

.user-posts, .user-comments {
  padding: 10px;
}

.post-item, .comment-item {
  margin-bottom: 12px;
}

.empty-content {
  padding: 40px 0;
}

.user-detail-container {
  padding-bottom: 20px;
  background-color: #f7f8fa;
  min-height: 100vh;
}

.nav-header {
  position: sticky;
  top: 0;
  display: flex;
  align-items: center;
  height: 44px;
  padding: 0 16px;
  background-color: #fff;
  z-index: 100;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.back-button {
  font-size: 20px;
  color: #333;
  cursor: pointer;
}

.page-title {
  flex: 1;
  text-align: right;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}
</style>
